package com.demo.jvm.chapter3.mydynamic;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;

/**
 * Javaclass执行工具 * *
 *
 * @author zzm
 */
public class JavaclassExecuter {

  /**
   * 执行外部传过来的代表一个Java 类的Byte数组<br>
   * 将输入类的byte数组中代表ja va.lang.System的 CONS TANT_Utf8_info常量修改为劫持后的HackSystem 类
   * <p>
   * 执行方法为该类的static main(String[] args)方 法，输出结果为该类向System.out/err输出的信息
   *
   * @return 执行结果
   */
  public static String execute(byte[] classByte) {
    HackSystem.clearBuffer();
    ClassModifier cm = new ClassModifier(classByte);

    byte[] modiBytes = cm.modifyUTF8Constant("java/lang/System", "com/demo/jvm/chapter3/mydynamic/HackSystem");
    HotSwapClassLoader loader = new HotSwapClassLoader();
    Class clazz = loader.loadByte(modiBytes);
    try {
      Method method = clazz.getMethod("main", new Class[]{String[].class});
      method.invoke(null, new String[]{null});
    } catch (Throwable e) {
      e.printStackTrace(HackSystem.out);
    }
    return HackSystem.getBufferString();
  }

  public static void main(String[] args) throws IOException {
    InputStream is = new FileInputStream("/Users/lwg/SouceCode/private/lie-flat-club/example-demo/target/classes/com/demo/jvm/chapter3/mydynamic/Test.class");
    byte[] b = new byte[is.available()];
    is.read(b);
    System.out.println("执行结果" + execute(b));
  }
}